<?php

class Default_LoginController extends ExtLb_Controller_Action{
	
	private $loginSess;

    public function init()
    {
        /* Initialize action controller here */
    	$this->loginSess = new Zend_Session_Namespace('loginSess');
    	
    }

    public function indexAction()
    {
//        // action body
//    	if(!Zend_Auth::getInstance()->hasIdentity()){
////	    	$this->_redirect('default/login');
//    	}
    }
    
    public function loginAction(){
    	if(isset($_POST['cmdLogin'])){
    		
    		$user = $this->_getParam('txtUser');
    		$pass = md5($this->_getParam('txtPass'));

//    		echo $user . $pass;
    		$authAdapter = $this->getAuthAdapter();
    		$authAdapter->setIdentity($user)
    					->setCredential($pass);
    	
    		$auth = Zend_Auth::getInstance();
    		$result = $auth->authenticate($authAdapter);
    		if($result->isValid()){
    			
    			//LAY DU LIEU CAN THIET LUU VAO SESSION KHI DANG NHAP THANH CONG
    			//va loai bo cac field ko dc storage (trong array)
    			$identiy  = $authAdapter->getResultRowObject(NULL,array('matKhau'));
    			$auth->getStorage()->write($identiy);
    			
//    			echo $auth->getIdentity()->quyen. " ddd";
    			$this->jShowMessage("Đăng nhập thành công!!!");
    			
    			$this->_forward('index','index','admin');
    		}
    	}
    	
    	if(!Zend_Auth::getInstance()->hasIdentity()){
    		$this->_redirect('default/index');
    	}else {
//    		if(Zend_Auth::getInstance()->getIdentity()->quyen == "admin"){
//    			$this->_redirect('admin/index');	
//    		}
    		$this->_redirect('admin/index');
    	}
    }
    
    public function logoutAction(){
    	Zend_Auth::getInstance()->clearIdentity();
    	$this->_redirect('default/index');
    }
    
    
    
    private function getAuthAdapter(){
    	$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
    	$authAdapter->setTableName('nguoidung')
    				->setIdentityColumn('tenDangNhap')
    				->setCredentialColumn('matKhau');
    	return $authAdapter;
    }
	


}

